package com.hwz.gulimall.product.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hwz.common.utils.Query;
import com.hwz.gulimall.product.constant.AttrEnum;
import com.hwz.gulimall.product.dao.AttrGroupDao;
import com.hwz.gulimall.product.entity.AttrAttrgroupRelationEntity;
import com.hwz.gulimall.product.entity.AttrGroupEntity;
import com.hwz.gulimall.product.entity.CategoryEntity;
import com.hwz.gulimall.product.service.AttrAttrgroupRelationService;
import com.hwz.gulimall.product.service.AttrGroupService;
import com.hwz.gulimall.product.service.CategoryService;
import com.hwz.gulimall.product.vo.AttrRespVO;
import com.hwz.gulimall.product.vo.AttrVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hwz.common.utils.PageUtils;

import com.hwz.gulimall.product.dao.AttrDao;
import com.hwz.gulimall.product.entity.AttrEntity;
import com.hwz.gulimall.product.service.AttrService;
import org.springframework.util.CollectionUtils;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {

    @Autowired
    CategoryService categoryService;

    @Autowired
    AttrGroupDao attrGroupDao;



    @Autowired
    AttrAttrgroupRelationService attrAttrgroupRelationService;
    @Override
    public PageUtils queryPage(Map<String, Object> params, String  cateLogId, String attrType) {
        QueryWrapper<AttrEntity> queryWrapper = new QueryWrapper<>();

        queryWrapper.eq("attr_type", AttrEnum.AttrType.ATTR_TYPE_BASE.getName().equals(attrType)?AttrEnum.AttrType.ATTR_TYPE_BASE.getCode():AttrEnum.AttrType.ATTR_TYPE_SALE.getCode());

        if (StringUtils.isNotEmpty(cateLogId) && !"0".equals(cateLogId)){
            queryWrapper.eq("catelog_id", cateLogId);
        }

        String key = (String)params.get("key");
        if (StringUtils.isNotEmpty(key)){
            queryWrapper.and((obj)->{
                obj.eq("attr_id", key).or().like("attr_name", key);
            });
        }

        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                queryWrapper
        );


        List<AttrEntity> records = page.getRecords();
        List<AttrRespVO> resList = records.stream().map(item -> {
            AttrRespVO respVO = new AttrRespVO();
            BeanUtils.copyProperties(item, respVO);


            //查询分类信息
            CategoryEntity categoryEntity = categoryService.getById(item.getCatelogId());
            if (categoryEntity != null) {
                respVO.setCatelogName(categoryEntity.getName());

            }

            if (AttrEnum.AttrType.ATTR_TYPE_BASE.getName().equals(attrType)){
                //查询分组信息
                List<AttrAttrgroupRelationEntity> attrGroupList = attrAttrgroupRelationService.list(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", item.getAttrId()));
                if (!CollectionUtils.isEmpty(attrGroupList)) {
                    respVO.setGroupName(attrGroupList.stream().map(r -> {
                        AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(r.getAttrGroupId());
                        if (attrGroupEntity != null) {
                            return attrGroupEntity.getAttrGroupName();
                        }
                        return null;
                    }).collect(Collectors.joining(",")));

                }
            }


            return respVO;
        }).collect(Collectors.toList());

        Page<AttrRespVO> attrRespVOPage = new Page<>();
        BeanUtils.copyProperties(page, attrRespVOPage);
        attrRespVOPage.setRecords(resList);
        return new PageUtils(attrRespVOPage);
    }

    @Override
    public List<AttrEntity> getRelationAttr(Long attrgroupId) {
        List<AttrAttrgroupRelationEntity> relationEntities = attrAttrgroupRelationService.list(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_group_id", attrgroupId));


        List<Long> arrtIds = relationEntities.stream().map(item -> item.getAttrId()).collect(Collectors.toList());
        if (arrtIds.isEmpty()){
            return new ArrayList<>();
        }
        List<AttrEntity> list = this.list(new QueryWrapper<AttrEntity>().in("attr_id", arrtIds));


        return list;
    }

    @Override
    public Page getNoRelationAttr(Map<String, Object> params, Long attrgroupId) {

        QueryWrapper<AttrEntity> queryWrapper = new QueryWrapper<>();


        //获取这个分组的分类ID
        AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrgroupId);

        if (attrGroupEntity != null){
            queryWrapper.eq("catelog_id", attrGroupEntity.getCatelogId());
        }

        //查询当前分类下的所有分组ID
        List<AttrGroupEntity> attrGroups = attrGroupDao.selectList(new QueryWrapper<AttrGroupEntity>().eq("catelog_id", attrGroupEntity.getCatelogId()));
        List<Long> attrGroupIds = attrGroups.stream().map(item -> item.getAttrGroupId()).collect(Collectors.toList());


        //获取和这个分类下被关联的属性id
        List<AttrAttrgroupRelationEntity> records = attrAttrgroupRelationService.list(new QueryWrapper<AttrAttrgroupRelationEntity>().in("attr_group_id", attrGroupIds));
//        List<AttrAttrgroupRelationEntity> records = page.getRecords();
        List<Long> arrtIds = records.stream().map(item -> item.getAttrId()).collect(Collectors.toList());
        //如果有条件才加
        if (arrtIds != null && !arrtIds.isEmpty()){
            queryWrapper.notIn("attr_id", arrtIds);
        }

        if (params.get("key") != null && StringUtils.isNotEmpty((String) params.get("key"))){
            String key = (String)params.get("key");
            queryWrapper.and(wrapper ->
                    wrapper.like("attr_name", key)
                            .or()
                            .like("attr_id", key)
            );
        }

        IPage<AttrEntity>  page = this.page(new Query<AttrEntity>().getPage(params), queryWrapper);






        Page<AttrEntity> res = new Page<>();
        res.setRecords(page.getRecords());
        res.setTotal(page.getTotal());
        res.setPages(page.getPages());
        res.setCurrent(page.getCurrent());



        return res;
    }

    @Override
    public void save(AttrVO attr) {
        //添加属性到数据库
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr, attrEntity);
        this.save(attrEntity);

        if (AttrEnum.AttrType.ATTR_TYPE_BASE.getCode() == attr.getAttrType()){
            //维护属性与属性组的关系
            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = new AttrAttrgroupRelationEntity();
            attrAttrgroupRelationEntity.setAttrGroupId(attr.getAttrGroupId());
            attrAttrgroupRelationEntity.setAttrId(attrEntity.getAttrId());
            attrAttrgroupRelationService.save(attrAttrgroupRelationEntity);

        }

    }

    @Override
    public AttrRespVO getDetailById(Long attrId) {
        AttrEntity entity = this.getById(attrId);

        AttrRespVO respVO = new AttrRespVO();
        BeanUtils.copyProperties(entity, respVO);

        //查询groupId
        AttrAttrgroupRelationEntity relationEntity = attrAttrgroupRelationService.getOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrId).last("limit 1"));
        if (relationEntity != null){
            respVO.setAttrGroupId(relationEntity.getAttrGroupId());
        }

        //查询分类的完整路径
        Long[] catelogPath = categoryService.getCategoryPathById(entity.getCatelogId());
        respVO.setCatelogPath(catelogPath);


        return respVO;
    }

    @Override
    public void editById(AttrVO attr) {

        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr, attrEntity);
        //修改基础属性
        updateById(attrEntity);

        if (AttrEnum.AttrType.ATTR_TYPE_BASE.getCode() == attr.getAttrType()){

            //修改关联关系
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            relationEntity.setAttrId(attr.getAttrId());
            relationEntity.setAttrGroupId(attr.getAttrGroupId());

            int count = attrAttrgroupRelationService.count(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attr.getAttrId()));

            //如果没有就新建
            if (count == 0){
                attrAttrgroupRelationService.save(relationEntity);
            }else {
                attrAttrgroupRelationService.update(relationEntity, new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attr.getAttrId()));
            }

        }


    }

    @Override
    public List<Long> selectSearchAttrs(List<Long> attrIds) {
        List<Long> searchIds = this.listObjs(
                new QueryWrapper<AttrEntity>()
                        .select("attr_id")                // 只查询 id 列
                        .in("attr_id", attrIds)      // WHERE attr_id IN (1, 2, 3)
                        .ne("search_type", 0),       // AND search_type != 0
                obj -> (Long) obj                // 将 Object 转为 Long
        );
        return searchIds;
    }

}